﻿#include "uloadingdialog.h"
#include "widgets/ulabel.h"

#include <QEvent>
#include <QPainter>
#include <QVBoxLayout>

LoadingWidget::LoadingWidget(QWidget* parent) : QWidget(parent)
{
    initAnimation();
}

void LoadingWidget::setIconSize(const QSize &iconSize)
{
    if (m_iconSize != iconSize)
    {
        m_iconSize = iconSize;
        update();
    }
}

void LoadingWidget::setIcon(const QIcon &icon)
{
    m_icon = icon;
    update();
}

void LoadingWidget::start(int nTime)
{
    m_variantAnimation.setDuration(nTime);
    m_variantAnimation.start();
}

void LoadingWidget::stop()
{
    m_variantAnimation.stop();
}

void LoadingWidget::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

    if (!m_icon.isNull())
    {
        painter.save();
        QPointF point = QRectF(this->rect()).center();
        painter.translate(point);
        painter.rotate(m_angle);
        painter.translate(-point.x(), -point.y());
        m_icon.paint(&painter, QRect(QPoint(point.x() - m_iconSize.width() / 2, point.y() - m_iconSize.height() / 2), m_iconSize));
        painter.restore();
    }
}

void LoadingWidget::initAnimation()
{
    m_variantAnimation.setStartValue(0);
    m_variantAnimation.setEndValue(360);
    m_variantAnimation.setLoopCount(-1);
    connect(&m_variantAnimation, &QVariantAnimation::valueChanged, this, [this](const QVariant & value)
    {
        m_angle = value.toInt();
        update();
    });
}

LoadingDialog::LoadingDialog(QWidget* parent) : UDialog(parent)
{
    initUi();
}

void LoadingDialog::setIconSize(const QSize &iconSize)
{
    m_loadingWidget->setFixedSize(iconSize.width() + 10, iconSize.height() + 10);
    m_loadingWidget->setIconSize(iconSize);
}

void LoadingDialog::setIcon(const QIcon &icon)
{
    m_loadingWidget->setIcon(icon);
}

void LoadingDialog::start(int nTime)
{
    m_loadingWidget->start(nTime);
}

void LoadingDialog::stop()
{
    m_loadingWidget->stop();
}

void LoadingDialog::initUi()
{
    setTitleBarVisible(false);

    QWidget* widget = new QWidget(this);
    QVBoxLayout* mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);
    m_loadingWidget = new LoadingWidget(this);
    m_textLabel = new ULabel(this);
    mainLayout->addStretch();
    mainLayout->addWidget(m_loadingWidget, 0, Qt::AlignHCenter);
    mainLayout->addWidget(m_textLabel, 0, Qt::AlignHCenter);
    mainLayout->addStretch();
    widget->setLayout(mainLayout);

    setContentWidget(widget);
    setWindowModality(Qt::ApplicationModal);
    setFixedSize(236, 147);
}

void LoadingDialog::setText(const QString &text)
{
    m_textLabel->setText(text);
}

QString LoadingDialog::text()
{
    return m_textLabel->text();
}
